"use strict";
/*
* wgeFilterInterface.js
*
*  Created on: 2018-3-12
*      Author: Wang Yang
*        Blog: http://blog.wysaid.org
*        Mail: admin@wysaid.org
*/

WGE.FilterInterface = WGE.Class({

    vertexShader : "" +
    "attribute vec2 position;\n" +
    "varying vec2 textureCoordinate;\n" +
    "uniform vec2 flipScale;\n" +
    "void main()\n" +
    "{\n" +
    "    gl_Position = vec4(position * flipScale, 0.0, 1.0);\n" +
    "    textureCoordinate = (position.xy + 1.0) / 2.0;\n" +
    "}",

    fragmentShader : "" +
    "precision mediump float;\n" +
    "varying vec2 textureCoordinate;\n" +
    "uniform sampler2D inputImageTexture;\n" +
    "void main()\n" +
    "{\n" +
    "    gl_FragColor = texture2D(inputImageTexture, textureCoordinate);\n" +
    "}",

    context : undefined,
    program : undefined,
    intensityLoc : undefined,
    attributePositionName : "position",
    flipScaleLoc : undefined,

    initialize : function (context, vsh, fsh) {
        this.context = context;
        if(vsh) {
            this.vertexShader = vsh;
        }

        if(fsh) {
            this.fragmentShader = fsh;
        }

        this.onInit();
    },

    onInit : function () {
        if(this.vertexShader && this.fragmentShader) {
            var program = this.program = new WGE.Program(this.context);
            program.bindAttribLocation(this.attributePositionName, 0);
            var ret = program.initWithShaderCode(this.vertexShader, this.fragmentShader);
            if(ret) {
                this.intensityLoc = program.uniformLocation("intensity");
                this.flipScaleLoc = program.uniformLocation("flipScale");
                this.setFlipScale(1, 1);
            } else {
                program.release();
                this.program = null;
            }
        }
    },

    render : function (handler, srcTex, buffer, fbo) {
        var gl = this.context;
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, srcTex);

        gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        gl.enableVertexAttribArray(0);
        gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);

        this.program.bind();

        gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
    },

    setIntensity : function (intensity) {
        if(this.intensityLoc) {
            this.program.bind();
            this.context.uniform1f(this.intensityLoc, intensity);
        }
    },

    setFlipScale : function (x, y) {
        if(this.flipScaleLoc) {
            this.program.bind();
            this.context.uniform2f(this.flipScaleLoc, x, y);
        }
    },

    isValid : function () {
        return !!this.program;
    }

});